package 网络编程.socket;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * @author Y·C
 * @version 1.0.0
 * @ClassName SocketTCP01Server.java
 * @Description 服务端，使用字符流
 * @createTime 2023年05月03日 14:57:00
 */
@SuppressWarnings({"all"})
public class SocketTCP03Server {
    public static void main(String[] args) throws IOException {
        /**
         * 思路
         * 1.在本机的9999端口监听，等待连接
         * 2.当没有客服端连接9999端口时，程序会阻塞，等待连接
         * 3.通过socket.getInputSteam()读取客服端写入到数据通道的数据，显示
         * */

        //在本机的9999端口监听，等待连接
        // 细节：这个ServerSocket 可以通过 accept()返回多个Socket[多个客服端连接服务器的并发]
        ServerSocket serverSocket = new ServerSocket(9999);
        System.out.println("服务端，在9999端监听，等待连接");
        //当没有客服端连接9999端口时，程序会阻塞，等待连接
        //如果有客服端连接，则会返回Socket对象,程序继续
        Socket socket = serverSocket.accept();
        System.out.println("服务端socket = " + socket.getClass());
        //通过socket.getInputSteam()读取客服端写入到数据通道的数据，显示
        InputStream inputStream = socket.getInputStream();
        //4.IO读取,使用字节流 使用InputStreamReader 将 inputStream 转成字符流
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
        String s = bufferedReader.readLine();
        System.out.println(s);

        //5.获取socket相关联的输出流
        OutputStream outputStream = socket.getOutputStream();
        BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream));
        bufferedWriter.write("hello,client 字符流");
        bufferedWriter.newLine();
        bufferedWriter.flush();

        bufferedReader.close();
        bufferedWriter.close();
        socket.close();
        serverSocket.close();
        outputStream.close();

    }
}
